// pages/friends/index.ts
import tran from "../../utils/language";
import {
  eqTestResult,
  eqAll,
  userChatStatistics,
  userMobile,
  login,
} from "../../utils/api";
import dayjs from "dayjs";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    _t: tran._t("metrics"),
    _tBase: tran._t("base"),
    navBarHeight: getApp().globalData.navBarHeight,
    eqList: [
      {
        timeText: "",
      },
    ],
    articleList: [],
    loginInfo: {},
    chatList: [],
    mobileCode: "",
    hasMobile: false,
    popupParams: {
      showPopup: false,
      showType: 0, // 0 注册 1 登录
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log('show');
    this.setData({
      eqList: [],
      articleList: [],
      loginInfo: {
        fullName: '',
        nickname: '',
      }
    });
    console.log(this.data.loginInfo, 5566);
    getApp().updateTabBar(getApp().globalData.totalUnread);
    if (typeof this.getTabBar === "function" && this.getTabBar()) {
      this.getTabBar().setData({
        activeKey: "metrics",
      });
    }
    const isLoginFlag = this.isLogin();
    const loginInfo = wx.getStorageSync("userInfo");
    
    this.setData({
      loginInfo,
    });
    if (isLoginFlag) {
      this.getArticle();
      this.getChat();
      this.getEqList();
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() { },
  resetTap() {
    const { eqList } = this.data;
    const obj = eqList.length > 0 ? eqList[0] : {};
    const infoStr = JSON.stringify(obj);
    wx.redirectTo({
      url: `/pages/profile/eqTestQuestion/index?info=${infoStr}`,
    });
  },
  getLogin() {
    const loginInfo = wx.getStorageSync("loginInfo");
    if (loginInfo) {
      this.goRegister();
    } else {
      this.getLoginToken(3);
    }
  },
  /**
   * 拿到token
   */
  getLoginToken(getMobileFlag: any) {
    const that = this;
    wx.login({
      success(res1) {
        if (res1.code) {
          // 调用登录的接口
          const params = {
            code: res1.code,
          };
          login(params).then((res: any) => {
            const { header, data } = res;
            let loginInfo = data.data;
            that.openShowLoginPopup(data);
            let token =
              header["Frieneed-Mini-Program-Satoken"] ||
              header["frieneed-mini-program-satoken"];
            let key =
              header["Access-Control-Expose-Headers"] ||
              header["access-control-expose-headers"]; // 用户的token放在response里面返回的
            let obj = {
              token,
              key,
              ...loginInfo,
            };
            that.setData({
              completedStep: obj.completedStep,
              hasMobile: loginInfo.hasMobile,
            });
            wx.setStorage({
              key: "loginInfo",
              data: obj,
              success() {
                // 调用获取个人信息的接口
                getApp().getUserInfo();
                if (getMobileFlag == 2) {
                  // 获取用户手机号
                  that.getMobile();
                }
                // 调用成功后，查询列表数据
                that.getArticle();
                that.getChat();
                that.getEqList();
              },
            });
          });
        } else {
          wx.showToast({
            title: "网络异常",
            icon: "none",
          });
        }
      },
    });
  },
  openShowLoginPopup(obj: any) {
    const { popupParams } = this.data;
    popupParams.showPopup = false;
    // popupParams.showType = obj.hasMobile == true && obj.completedStep == 5 ? 2 : 0 // 0 注册 1 登录
    // 关闭弹框
    this.setData({ popupParams, completedStep: obj.completedStep });
  },
  getPhoneNumber(e: baseEvent) {
    const that = this;
    if (e.detail.errMsg === "getPhoneNumber:ok") {
      // 获取到加密数据
      const { encryptedData, iv, code } = e.detail;
      that.setData(
        {
          mobileCode: code,
        },
        () => {
          that.getLoginToken(2);
        }
      );
      // 调用登录的接口
      // that.getMobile()
    } else {
      console.warn("用户拒绝授权");
    }
  },
  /**
   * 调用更新手机号的接口
   */
  getMobile() {
    const that = this;
    const params = {
      code: this.data.mobileCode,
    };
    userMobile(params).then((res: any) => {
      const { popupParams } = that.data;
      popupParams.showPopup = false;
      popupParams.showType = 1;
      // 关闭弹框
      that.setData({ popupParams, hasMobile: true });
      getApp().getUserInfo();
      that.goRegister();
    });
  },
  /**
   * 跳转去注册
   */
  goRegister() {
    this.onClosePopup();
    wx.navigateTo({
      url: "/pages/profile/create-account/index?type='register'",
    });
  },
  onClosePopup() {
    const { popupParams } = this.data;
    popupParams.showPopup = false;
    this.setData({
      popupParams,
    });
    // const customPopup = this.selectComponent('#custom-popup');
    // customPopup && customPopup.hidePopup()
  },
  isLogin() {
    const userInfo = wx.getStorageSync("userInfo");
    const loginInfo = wx.getStorageSync("loginInfo") || {};
    this.setData({
      hasMobile: loginInfo.hasMobile,
      completedStep: loginInfo.completedStep,
    });
    if (Object.keys(loginInfo).length > 0 && loginInfo.completedStep == 5) {
      this.setData({
        loginInfo: userInfo,
        completedStep: loginInfo.completedStep,
        hasMobile: loginInfo.hasMobile,
      });
      return true;
    } else {
      this.setData({
        completedStep: 0,
        hasMobile: false,
      });
      return false;
    }
  },
  openLoginPopup() {
    const { popupParams } = this.data;
    popupParams.showPopup = true;
    this.setData({
      popupParams,
    });
  },
  goEqResult(e: any) {
    // const isLoginFlag = this.isLogin()
    const isLoginFlag = this.checkRegister();
    let { popupParams } = this.data;
    if (isLoginFlag) {
      const info = e.currentTarget.dataset.info;
      const infoStr = JSON.stringify(info);
      wx.navigateTo({
        url: `/pages/profile/eqTestResult/index?info=${infoStr}`,
      });
    } else {
      this.setData(
        {
          popupParams,
        },
        () => {
          this.openLoginPopup();
        }
      );
    }
  },
  /**
   * 检查是否登录注册
   */
  checkRegister() {
    const userInfo = wx.getStorageSync("userInfo") || {};
    const loginInfo = wx.getStorageSync("loginInfo") || {};
    const { popupParams } = this.data;
    popupParams.showPopup = true;
    // hasMobile有手机号，说明是已经获取了手机号，显示登录按钮，否则显示注册按钮（获取手机号）
    popupParams.showType = loginInfo.hasMobile ? 1 : 0; // 0注册 1登录
    this.setData({
      hasMobile: loginInfo.hasMobile,
      completedStep: loginInfo.completedStep,
    });
    if (Object.keys(loginInfo).length == 0) {
      // 没有登录信息，就登录
      popupParams.showType = 1;
      return false;
    }
    if (
      userInfo &&
      Object.keys(userInfo).length > 0 &&
      loginInfo.completedStep == 5
    ) {
      return true;
    } else {
      popupParams.showType = 0;
      this.setData({
        popupParams,
      });
      return false;
    }
  },
  goArticle(e: any) {
    const info = e.currentTarget.dataset.info;
    const infoStr = JSON.stringify(info);
    wx.navigateTo({
      url: `/pages/profile/recommendArticle/index?info=${infoStr}`,
    });
  },
  goStatisticsData() {
    wx.navigateTo({
      url: `/pages/profile/participationStatistics/index`,
    });
  },
  getArticle() {
    const params = {};
    eqAll(params).then((res) => {
      if (res && Object.keys(res).length > 0) {
        // if (res.code == 200) {
        this.setData({
          articleList: res.eqArticles,
        });
      } else {
        this.setData({
          articleList: [],
        });
      }
    });
  },
  getChat() {
    const params = {};
    userChatStatistics(params).then((res) => {
      if (res.code == 200) {
        this.setData({
          chatList: res || [],
        });
      }
    });
  },
  /**
   * 开始eq测试
   */
  goEqTest() {
    const { eqList } = this.data;
    const isLoginFlag = this.checkRegister();
    if (isLoginFlag) {
      let url = "/pages/profile/eqTestQuestion/index";
      if (eqList.length > 0) {
        const info = eqList.length > 0 ? eqList[0] : {};
        const infoStr = JSON.stringify(info);
        url = `/pages/profile/eqTestQuestion/index?info=${infoStr}`;
      }
      wx.navigateTo({
        url: url,
      });
    } else {
      this.openLoginPopup();
    }
  },
  /**
   * 获取eq列表
   */
  getEqList() {
    const params = {};
    eqTestResult(params).then((res) => {
      if (res && Object.keys(res).length > 0) {
        if (res.scoreAssessments) {
          const timeText =
            res.createTime && res.createTime != "0"
              ? dayjs(res.createTime).format("YYYY/MM/DD")
              : "";
          let list: any = [
            {
              ...res,
              timeText,
            },
          ];
          this.setData({
            eqList: list || [],
          });
        } else {
          this.setData({
            eqList: [],
          });
        }
      }
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() { },
});
